// pages/list-page/academy-list/academy-list.js
let self
var app = getApp();
const { FILTERS } = require('../../config/filters.js');
const { mayjorList, schoolList, rulesList, addressList } = require('../../config/api/index.js');
Page({

  /**
   * 页面的初始数据
   */
	data: {
		isloading: true,
		moreCoursesLoading: false,  // 加载更多课程的状态
		listData: [],
		filters: [],
		currentFilter: [],  // 当前选择的筛选
		general: false,  // 是否为招生简章页面
		menuState: true,  // 菜单状态
		currentMenu: {},
		openState: false,  // 列表按钮菜单显示状态
		maskState: false,
		pageType: 'academy',  // 页面属性
		curPage: 1,  // 当前页
		perPage: 10,  // 每页的数量
		noMoreState: false,  // 没有更多数据
		filterText: '',  // 筛选或者搜索的文本wxRequest
		filterPage: 1,
		filterType: '',  // 筛选类型
		addressPage: 1,
		mayjorPage: 1,
		school: [],  // 全部学校
		address: [],  // 全部地区
		mayjor: [],  // 全部专业
		area: '',  // 地区id
		project: '',  // 专业id
		schoolid: '',  // 学校id
		class_type: '',  // 班型id
		searchPlaceholder:'请输入学校或简章名称'
	},
  /**
   * 生命周期函数--监听页面加载
   */
	onLoad: function (options) {
		self = this;
		let filters = FILTERS[options.filters] || FILTERS['academy']  // 获取对应列表页静态数据
		wx.setNavigationBarTitle({
			title: options.title || '找学校'
		})
		self.setData({
			filters: filters.data,
			title: options.title || '找学校',
			pageType: options.filters || 'academy',
			area: options.areaId || '',
			project: options.matjorId || '',
			filterText: options.searchVal || '',
			schoolid: options.id || ''
		})
		self.setData({
			general: (options.filters == 'general' || options.filters == 'school' || options.filters == 'major' || options.filters == 'address') ? true : false
		})
	
		let currentFilter = {
			area: self.data.area || '',
			project: self.data.project || '',
			school: self.data.schoolid || '',
			class_type: self.data.class_type || '',
			search: self.data.filterText || '',
		}
		for (let key in currentFilter) {              // 去除对象内多余的空值key  
			if (currentFilter[key] === '') {
				delete currentFilter[key]
			}
		}
		self.setData({ currentFilter})
	
		if (self.data.pageType == 'academy') {  // 调取学校列表
			self.getSchoolList()
			self.getAddressList()
		}
		if (self.data.pageType == 'general') {  // 调取简章列表
			self.geRulesList(currentFilter)
			self.getAddressList()
			self.getMayjorList()
			self.getSchoolFilter()
			
		}
		if (self.data.pageType == 'school') {
			self.geRulesList(currentFilter)
			self.getAddressList()
			self.getMayjorList()
			self.setData({
				searchPlaceholder: '请输入简章名称',
			})
	
		}
		if (self.data.pageType == 'address') {
			self.getMayjorList(1)
			self.getSchoolFilter()
			self.geRulesList(currentFilter)
		}
		if (self.data.pageType == 'major') {
			self.getAddressList()
			self.getSchoolFilter()
			self.geRulesList(currentFilter)
		}
	},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function () {

	},
	getSchoolList(params, extend) { // 获取学校列表
		const { perPage, listData } = self.data;
		return schoolList({
			data: {
				...{
					per_page: perPage,
					is_get: 1
				},
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages
				if (extend) {
					let curPage = Math.ceil((listData.length + res.data.items.length) / perPage);
					self.setData({
						listData: [...listData, ...res.data.items],
						curPage,
						noMoreState: parseInt(totalPages) <= curPage
					})
				} else {
					self.setData({
						listData: res.data.items,
						curPage: 1,
						noMoreState: parseInt(totalPages) <= Math.ceil(res.data.items.length / perPage)
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false,
					moreCoursesLoading: false,
				})
			}

		})

	},
	geRulesList(params, extend) {  // 获取简章列表
		const { perPage, listData } = self.data;
		return rulesList({
			data: {
				...{
					is_get: 1,
					per_page: perPage,
				},
				...params
			},
			success(res) {
				let totalPages = res.data.total_pages
				res.data.items.forEach((item)=>{
					item.price = item.price.split('.')[0]
				})
				if (extend) {
					let curPage = Math.ceil((listData.length + res.data.items.length) / perPage);
					self.setData({
						listData: [...listData, ...res.data.items],
						curPage,
						noMoreState: parseInt(totalPages) <= curPage
					})
				} else {
					self.setData({
						listData: res.data.items,
						curPage: 1,
						noMoreState: parseInt(totalPages) <= Math.ceil(res.data.items.length / perPage)
					})
				}
			},
			complete(res) {
				self.setData({
					isloading: false,
					moreCoursesLoading: false,
					menuState: true
				})
			}

		})
	},
	getAddressList(param) {  // 获取全部地区列表
		const { perPage, addressPage, address } = self.data;
		return addressList({
			data: { per_page:100, ...param },
			success(res) {
				let totalPages = res.data.total_pages
				if (addressPage <= totalPages) {
					self.setData({
						addressPage: addressPage + 1,
						address: [...address, ...res.data.items,]
					})
					setTimeout(function () {
						self.getAddressList({ page: addressPage + 1 })
					}, 0)
				} else {
					let data = self.data.address
					let address = [];
					for (let i = 0; i < data.length; i++) {
						if (data[i].level === '2') {
							address.push({
								typeid: data[i].id,
								val: data[i].name,
								lists: []
							})
						}
					}
					let filters = self.data.filters
					let index = 2
					if (self.data.pageType == 'academy') {
						index = 0
					}
					if (self.data.pageType == 'school') {
						index = 1
					}
					if (self.data.pageType == 'major') {
						index = 1
					}
					filters[index].lists = address
					self.setData({
						filters
					})
				}
			}
		})


	},
	getMayjorList(param) {  // 获取全部专业列表
		const { perPage, mayjorPage, mayjor } = self.data;
		return mayjorList({
			data: { per_page:100, ...param},
			success(res) {
				let totalPages = res.data.total_pages
				if (mayjorPage <= totalPages) {
					self.setData({
						mayjorPage: mayjorPage + 1,
						mayjor: [...mayjor, ...res.data.items]
					})
					setTimeout(function () {
						self.getMayjorList({ page: mayjorPage + 1 })
					}, 0)
				} else {
					let data = self.data.mayjor
					let matjor = [];
					for (let i = 0; i < data.length; i++) {
						if (data[i].pid === '3') {
							matjor.push({
								typeid: data[i].id,
								val: data[i].name,
								lists: []
							})
						}
					}
					for (let j = 0; j < data.length; j++) {
						let currentItem = matjor.find(item => {
							return data[j].pid === item.typeid
						})
						if (currentItem) {
							currentItem.lists.push({
								typeid: data[j].id,
								val: data[j].name,
								lists: []
							})
						}
					}
					matjor.map(item => {
						let arr = item.lists
						for (let n = 0; n < data.length; n++) {
							let currentItem = arr.find(item => {
								return data[n].pid === item.typeid
							})
							if (currentItem) {
								currentItem.lists.push({
									typeid: data[n].id,
									val: data[n].name,
									pid: data[n].pid,
									lists: []
								})
							}
						}
					})
					


					let filters = self.data.filters
					if (self.data.pageType == 'school'){
						filters[0].lists = matjor
					} else {
						filters[1].lists = matjor
					}
				
					self.setData({
						filters
					})
				}
			}
		})
	},
	getSchoolFilter(params) {  // 获取全部学校列表
		const { perPage, listData, filterPage, school } = self.data;

		return schoolList({
			data: {
				...{
					per_page: perPage,
					is_get: 1
				},
				...params
			},
			success(res) {

				let totalPages = res.data.total_pages
				if (filterPage <= totalPages) {
					self.setData({
						filterPage: filterPage + 1,
						school: [...school, ...res.data.items]
					})
				
					setTimeout(function () {
						self.getSchoolFilter({ page: filterPage + 1 })
					}, 0)
				} else {
					let filters = self.data.filters
			
					filters[0].lists = school
					self.setData({
						filters
					})
				}
		
			}
		})
	},
	onShow: function (e) {
	
	},
	onmask(e) {
		this.setData({
			maskState: false
		})
	},
	onMenuDown(e) {
		self.setData({
			menuState:false,
			filterType: e.detail
		})
	},
	onReset(e) {
		self.geRulesList({
			area: self.data.area || '',
			project: self.data.project || '',
			school: self.data.schoolid || '',
			class_type: '',
			search: '',
		})
	},
	onCurrent(e) {
		self.setData({
			listData: [],
			isloading: false
		})
		let category = [];
		wx.showLoading({
			title: '加载中...',
		})
	
		for (let k in e.detail) {
			category = [];
			category.push(e.detail)
		}
		self.setData({
			area: self.data.pageType == 'address' ? self.data.area : category[0]['address'] || '',
			project: self.data.pageType == 'major' ? self.data.project : category[0]['majoy'] || '',
			schoolid: self.data.pageType == 'school' ? self.data.schoolid : category[0]['school'] || '',
			class_type: category[0]['classType'] || '',
		})

		let currentFilter = {
			area: self.data.area || category[0]['address'] || '',
			project: self.data.project || category[0]['majoy'] || '',
			school: self.data.schoolid || category[0]['school'] || '',
			class_type: category[0]['classType'] || '',
			search: self.data.filterText || '',
		}
		self.setData({
			currentFilter
		})
		for (let key in currentFilter) {              // 去除对象内多余的空值key  
			if (currentFilter[key] === '') {
				delete currentFilter[key]
			}
		}
		if (self.data.pageType == 'academy') {  // 调取学校列表
			self.getSchoolList({})
		} else {
			let filterType = self.data.filterType					
			self.geRulesList(currentFilter)
		}
	},
	showDetail: function (e) {
		wx.navigateTo({
			url: '/pages/rules-detail/rules-detail?id=' + e.detail,
		})
	},
	showList: function (e) {
		let filtertit = e.currentTarget.dataset.filtertit
		wx.reLaunch({
			url: '/pages/list-page/list-page?filters=general&title=' + filtertit,
		})
	},
	searchCourses(e) {
		// 执行搜素
		self.setData({
			listData: [],
			isloading: false
		})
		wx.showLoading({
			title: '加载中...',
			mask: true
		})
		setTimeout(function () {
			wx.hideLoading()
		}, 2000)
		self.setData({
			filterText: e.detail,
			area: self.data.pageType == 'address' ? self.data.area : '',
			project: self.data.pageType == 'major' ? self.data.project : '',
			schoolid: self.data.pageType == 'school' ? self.data.schoolid  : '',
			class_type: '',
			isloading: false
		})
	
		let currentFilter = {
			area: self.data.pageType == 'address' ? self.data.area : '',
			project: self.data.pageType == 'major' ? self.data.project : '',
			school: self.data.pageType == 'school' ? self.data.schoolid : '',
			class_type: '',
			search: self.data.filterText || '',
		}
		self.setData({
			currentFilter
		})

		self.geRulesList(currentFilter, true)
		
	},
	blockCatch: function () {
		//阻断外层点击时间进入客服消息
		self.setData({
			openState: true
		})
	},
	onShareAppMessage: function (res) {
		return {
			title: '在职研究生网' + self.data.title,
			path: '/pages/list-page/list-page'
		}
	},
	onReachBottom() {
		// 加载更多
		if (self.data.noMoreState) {
			return false;
		}
		self.setData({
			moreCoursesLoading: true,
		})
		let currentFilter = self.data.currentFilter;
		for (let key in currentFilter) {              // 去除对象内多余的空值key  
			if (currentFilter[key] === '') {
				delete currentFilter[key]
			}
		}
		self.geRulesList({
			page: self.data.curPage + 1, 
			...currentFilter
		}, true)
		
	}
})